import React, { useState } from "react";
import '../css/login.css'

import {useNavigate} from 'react-router-dom' //路由
import { UserOutlined  } from '@ant-design/icons'; //图标
import { Button, Input} from 'antd'; //ui
import { message, } from 'antd'
import _ from 'lodash'//lodash防抖
// 接口
import logins from "../api/login";

const Login =()=> {

  const navigate = useNavigate() //路由

  const [user,setuser] = useState({  // useState可以传入初始值,返回状态与修改状态的函数
    admin_name: 'admin',
    pwd:'123456'
  })
  // console.log(user.name);


  // 账号
  let zhanghao =(e:any)=>{
    // this.setState({ //类组件的写法
    //   name:e.target.value
    // })

    setuser({  //函数组件的写法
      ...user,admin_name:e.target.value
    })
  }

  // 密码
  let mima =(e:any)=>{
    // this.setState({
    //   pass:e.target.value
    // })

    setuser({   //函数组件的写法
      ...user,pwd:e.target.value
    })
  }

  // 点击登录存数据
  const login = _.debounce(async()=>{
    let res:any = await logins(user)
    console.log(111,res);
    if(res.code==='00000'){
      message.success('登录成功',2)
      navigate('/index/Visitorindex')
      sessionStorage.setItem('login',user.admin_name)
      sessionStorage.setItem('token',res.token)
      sessionStorage.setItem('admin_id',res.admin.admin_id)
    }else{
      message.error(`${res.msg}`, 2);
    }
  },500)

  // 回车登录
  const onKeyup=(e:any)=> {
    if(e.keyCode === 13) {
      login()
    }
}
  // let login = async()=>{    
  //   let res:any = await logins(user)
  //   console.log(111,res);
  //   if(res.code==='00000'){
  //     message.success('登录成功',2)
  //     navigate('/index/Visitorindex')
  //     sessionStorage.setItem('login',user.admin_name)
  //     sessionStorage.setItem('token',res.token)
  //     sessionStorage.setItem('admin_id',res.admin.admin_id)
  //   }else{
  //     message.error(`${res.msg}`, 2);
  //   }
  // }
  
    return ( 
      <>
        <div className="login-box"> 
          <div className="input-box">
            <h2>登录</h2>
            <Input size="large" placeholder="请输入账号" prefix={<UserOutlined />} value={user.admin_name} 
              onChange={zhanghao} onKeyUp={onKeyup}/>
            <Input.Password placeholder="请输入密码" className="pass" value={user.pwd} onChange={mima} onKeyUp={onKeyup}/>

            <Button type="primary" className="butt" onClick={login}>登录</Button>
          
          </div>
        </div>
      </>
    );
}

export default Login
